package cn.gson.crm.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.interceptor.JsonResult;
import cn.gson.crm.model.dao.DeptDao;
import cn.gson.crm.model.dao.ResourcesDao;
import cn.gson.crm.model.dao.RoleDao;
import cn.gson.crm.model.entity.Dept;
import cn.gson.crm.model.entity.Resources;
import cn.gson.crm.model.entity.Role;
import cn.gson.crm.model.mapper.DeptMapper;

/**
 * 角色controller
 * @author Lenovo
 *
 */
@Controller
@RequestMapping("/role")
public class RoleController {
	@Autowired
	private DeptMapper roleMapper;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private ResourcesDao resDao;
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String,Object> index(Role role, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Role> pageData = roleMapper.listRole(role);

		PageInfo<Role> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> delete(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Role r;
		if (id != null && (r = roleDao.findOne(id)) != null) {
			r.setDelete(false);
			obj.put("success", true);
		} else {
			obj.put("message", "此角色不存在！");
		}
		return obj;
	}
	
	@GetMapping({ "add_role", "add_role/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			Role r = roleDao.findOne(id);
			if (r != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("role", r);
			}
		}
		return "role/add_role";
	}
	
	 @PostMapping("save")
	    @ResponseBody
	    @Transactional
	    public JsonResult form(@Valid Role role, BindingResult br) {
	        if (!br.hasErrors()) {
	        	if(role.getId() != null) {
	        		Role r = roleDao.findOne(role.getId());
	        		r.setEnable(role.getEnable());
	        		r.setName(role.getName());
	        		r.setRemark(role.getRemark());
	        		r.setRoleKey(role.getRoleKey());
	        		roleDao.save(r);
	        	}else {
	        	role.setDelete(true);
	            roleDao.save(role);
	        }
	            return JsonResult.success();
	        } else {
	            return JsonResult.error("校验不通过！");
	        }
	    }
	   @RequestMapping("permission/tree")
	    @ResponseBody
	    public List<Resources> permissionTree() {
	        return resDao.findAllByParentIsNull();
	    }
	   
	   /**
	     * 获取角色对应的权限列表
	     *
	     * @param id
	     * @return
	     */
	    @RequestMapping("permission/{id}")
	    @ResponseBody
	    public Set<Resources> permission(@PathVariable("id") Long id) {
	        Role role = roleDao.findOne(id);
	        return role.getResources();
	    }
	    
	    @RequestMapping("permission/save")
	    @Transactional
	    @ResponseBody
	    public JsonResult permissionSave(Long roleId, Long[] permissionId) {
	        Role role = roleDao.findOne(roleId);
	        //先清除已有角色
	        role.getResources().clear();
	        for (Long pid : permissionId) {
	            role.getResources().add(resDao.findOne(pid));
	        }

	        roleDao.save(role);

	        return JsonResult.success("授权成功！");
	    }
}
